<template>
	<view class="content">
		<view class="loginBg">
			<view class="logo">
				<u-image src="../../static/img/logo.png" width="48" height="48"></u-image>
				<text>中国节能</text>
			</view>
		</view>
		<view class="uform">
			<u-form>
				<u-form-item>
					<u-input v-model="form.userName" placeholder="用户名" type="text">
						<template slot="prefix">
							<u-image src="../../static/img/me/username.png" width="16" height="16"></u-image>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item>
					<u-input v-model="form.password" placeholder="密码" type="password">
						<template slot="prefix">
							<u-image src="../../static/img/me/password.png" width="16" height="16"></u-image>
						</template>
					</u-input>
				</u-form-item>
				<u-form-item>
					<view class="code">
						<u-input v-model="form.code" placeholder="验证码" type="text">
							<template slot="prefix">
								<u-image src="../../static/img/me/password.png" width="16" height="16"></u-image>
							</template>
						</u-input>
						<view style="width: 10rpx;"></view>
						<u-image mode="aspectFit" @click="getCode" :src="img" width="117" height="44"></u-image>
					</view>
				</u-form-item>
				<u-form-item>
					<u-button type="primary" text="登录" @click="handleLogin"></u-button>
				</u-form-item>
			</u-form>
		</view>
	</view>
</template>

<script>
	import {
		code,
		login
	} from '@/config/api'
	export default {
		data() {
			return {
				form: {
					enterpriseName: 'administrator',
					userName: 'admin',
					password: 'admin123',
					code: '',
				},
				img: '',
				uuid: '',
			}
		},
		onLoad() {
			this.getCode();
		},
		methods: {
			async getCode() {
				const res = await code();
				this.img = 'data:image/png;base64,' + res.img;
				this.uuid = res.uuid;
			},
			async handleLogin() {
				const params = {
					...this.form,
					uuid: this.uuid
				};
				try {
					const res = await login(params);
					uni.setStorageSync("access_token", res.access_token);
					uni.$u.toast('登录成功');
					uni.switchTab({
						url: '/pages/index/index',
					})
				} catch (e) {
					//TODO handle the exception
					this.getCode()
					this.form.code = undefined
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.loginBg {
		background-image: url('../../static/img/me/login_bg.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;
		height: 320rpx;
		position: relative;
	}

	.logo {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: absolute;
		top: 80%;
		left: 42%;
	}

	/deep/.u-form {
		margin-top: 120rpx;
		padding: 32rpx;
	}

	.code {
		display: flex;
		flex-direction: row;
	}
</style>